"""
天翼云盘适配器

将现有的Cloud189Client适配到BaseCloudProvider接口。
"""

import os
from typing import Dict, List, Optional, Any, Union
from ..base import BaseCloudProvider, CloudFile, UploadResult, DownloadResult, FileType
from .client import Cloud189Client


class TianyiAdapter(BaseCloudProvider):
    """天翼云盘适配器，将Cloud189Client适配到BaseCloudProvider接口"""
    
    def __init__(self, config: Dict[str, Any]):
        """
        初始化天翼云盘适配器
        
        Args:
            config: 配置参数，包含username, password, account_id等
        """
        super().__init__(config)
        
        self.username = config.get('username', '')
        self.password = config.get('password', '')
        self.account_id = config.get('account_id', 1)
        self.enable_debug = config.get('enable_debug', False)
        
        # 创建底层客户端
        self.client = Cloud189Client(
            account_id=self.account_id,
            username=self.username,
            password=self.password,
            enable_debug=self.enable_debug
        )
    
    def login(self) -> bool:
        """
        登录天翼云盘
        
        Returns:
            bool: 登录是否成功
        """
        return self.client.login()
    
    def logout(self) -> bool:
        """
        登出天翼云盘
        
        Returns:
            bool: 登出是否成功
        """
        return self.client.logout()
    
    def list(self, path: str = "/", recursive: bool = False) -> List[CloudFile]:
        """
        列出文件和文件夹
        
        Args:
            path: 路径，默认为根目录
            recursive: 是否递归列出子目录
            
        Returns:
            List[CloudFile]: 文件列表
        """
        try:
            # 将路径转换为文件夹ID
            folder_id = self._path_to_folder_id(path)
            
            # 获取文件列表
            files_data = self.client.get_files(folder_id)
            if not files_data:
                return []
            
            files = []
            for file_data in files_data.get('fileList', []):
                cloud_file = self._convert_to_cloud_file(file_data, path)
                if cloud_file:
                    files.append(cloud_file)
                    
                    # 如果是递归模式且当前是文件夹，继续获取子文件
                    if recursive and cloud_file.is_dir():
                        sub_path = os.path.join(path, cloud_file.name).replace('\\', '/')
                        sub_files = self.list(sub_path, recursive=True)
                        files.extend(sub_files)
            
            return files
            
        except Exception as e:
            print(f"列出文件异常: {e}")
            return []
    
    def upload(self, local_path: str, remote_path: str, 
               rapid_upload: bool = True) -> UploadResult:
        """
        上传文件
        
        Args:
            local_path: 本地文件路径
            remote_path: 远程文件路径
            rapid_upload: 是否尝试秒传
            
        Returns:
            UploadResult: 上传结果
        """
        try:
            if not os.path.exists(local_path):
                return UploadResult(False, message="本地文件不存在")
            
            # 解析远程路径
            parent_path, filename = os.path.split(remote_path)
            parent_id = self._path_to_folder_id(parent_path)
            
            # 上传文件
            result = self.client.upload_file(local_path, filename, parent_id)
            
            if result:
                return UploadResult(
                    success=True,
                    file_id=result.get('id', ''),
                    message="上传成功",
                    rapid_upload=result.get('rapid_upload', False)
                )
            else:
                return UploadResult(False, message="上传失败")
                
        except Exception as e:
            return UploadResult(False, message=f"上传异常: {e}")
    
    def download(self, remote_path: str, local_path: str) -> DownloadResult:
        """
        下载文件
        
        Args:
            remote_path: 远程文件路径
            local_path: 本地保存路径
            
        Returns:
            DownloadResult: 下载结果
        """
        try:
            # 获取文件信息
            file_info = self.get_file_info(remote_path)
            if not file_info:
                return DownloadResult(False, message="文件不存在")
            
            # 下载文件
            result = self.client.download_file(file_info.file_id, local_path)
            
            if result:
                return DownloadResult(
                    success=True,
                    message="下载成功",
                    local_path=local_path
                )
            else:
                return DownloadResult(False, message="下载失败")
                
        except Exception as e:
            return DownloadResult(False, message=f"下载异常: {e}")
    
    def delete(self, remote_path: str) -> bool:
        """
        删除文件或文件夹
        
        Args:
            remote_path: 远程文件路径
            
        Returns:
            bool: 删除是否成功
        """
        try:
            # 获取文件信息
            file_info = self.get_file_info(remote_path)
            if not file_info:
                return False
            
            # 删除文件
            return self.client.delete_file(
                file_info.file_id,
                file_info.name,
                file_info.is_dir()
            )
            
        except Exception as e:
            print(f"删除文件异常: {e}")
            return False
    
    def mkdir(self, path: str) -> bool:
        """
        创建文件夹
        
        Args:
            path: 文件夹路径
            
        Returns:
            bool: 创建是否成功
        """
        try:
            # 解析路径
            parent_path, folder_name = os.path.split(path)
            parent_id = self._path_to_folder_id(parent_path)
            
            # 创建文件夹
            result = self.client.create_folder_internal(folder_name, parent_id)
            return result is not None
            
        except Exception as e:
            print(f"创建文件夹异常: {e}")
            return False
    
    def move(self, src_path: str, dst_path: str) -> bool:
        """
        移动文件或文件夹
        
        Args:
            src_path: 源路径
            dst_path: 目标路径
            
        Returns:
            bool: 移动是否成功
        """
        try:
            # 获取源文件信息
            src_file = self.get_file_info(src_path)
            if not src_file:
                return False
            
            # 解析目标路径
            dst_parent_path, _ = os.path.split(dst_path)
            dst_parent_id = self._path_to_folder_id(dst_parent_path)
            
            # 移动文件
            return self.client.move_file(src_file.file_id, dst_parent_id)
            
        except Exception as e:
            print(f"移动文件异常: {e}")
            return False
    
    def copy(self, src_path: str, dst_path: str) -> bool:
        """
        复制文件或文件夹
        
        Args:
            src_path: 源路径
            dst_path: 目标路径
            
        Returns:
            bool: 复制是否成功
        """
        try:
            # 获取源文件信息
            src_file = self.get_file_info(src_path)
            if not src_file:
                return False
            
            # 解析目标路径
            dst_parent_path, dst_name = os.path.split(dst_path)
            dst_parent_id = self._path_to_folder_id(dst_parent_path)
            
            # 复制文件
            result = self.client.copy_file(src_file.file_id, dst_parent_id, dst_name)
            return result is not None
            
        except Exception as e:
            print(f"复制文件异常: {e}")
            return False
    
    def rename(self, src_path: str, new_name: str) -> bool:
        """
        重命名文件或文件夹
        
        Args:
            src_path: 源路径
            new_name: 新名称
            
        Returns:
            bool: 重命名是否成功
        """
        try:
            # 获取文件信息
            file_info = self.get_file_info(src_path)
            if not file_info:
                return False
            
            # 重命名文件
            if file_info.is_dir():
                return self.client.rename_folder(file_info.file_id, new_name)
            else:
                return self.client.rename_file(file_info.file_id, new_name)
                
        except Exception as e:
            print(f"重命名文件异常: {e}")
            return False
    
    def get_file_info(self, path: str) -> Optional[CloudFile]:
        """
        获取文件信息
        
        Args:
            path: 文件路径
            
        Returns:
            Optional[CloudFile]: 文件信息，如果不存在则返回None
        """
        try:
            # 解析路径
            parent_path, filename = os.path.split(path)
            if not filename:  # 根目录
                return CloudFile(
                    file_id="-11",
                    name="/",
                    size=0,
                    file_type=FileType.FOLDER,
                    path="/"
                )
            
            # 获取父目录文件列表
            parent_files = self.list(parent_path)
            
            # 查找目标文件
            for file in parent_files:
                if file.name == filename:
                    return file
            
            return None
            
        except Exception as e:
            print(f"获取文件信息异常: {e}")
            return None
    
    def get_download_url(self, path: str) -> Optional[str]:
        """
        获取文件下载链接
        
        Args:
            path: 文件路径
            
        Returns:
            Optional[str]: 下载链接，如果获取失败则返回None
        """
        try:
            # 获取文件信息
            file_info = self.get_file_info(path)
            if not file_info or file_info.is_dir():
                return None
            
            # 获取下载链接
            return self.client.get_download_url(file_info.file_id)
            
        except Exception as e:
            print(f"获取下载链接异常: {e}")
            return None
    
    def save_session(self, path: str) -> bool:
        """
        保存会话信息
        
        Args:
            path: 保存路径
            
        Returns:
            bool: 保存是否成功
        """
        try:
            return self.client.save_cache(path)
        except Exception as e:
            print(f"保存会话异常: {e}")
            return False
    
    def load_session(self, path: str) -> bool:
        """
        加载会话信息
        
        Args:
            path: 加载路径
            
        Returns:
            bool: 加载是否成功
        """
        try:
            return self.client.load_cache(path)
        except Exception as e:
            print(f"加载会话异常: {e}")
            return False
    
    def is_rapid_upload_supported(self) -> bool:
        """
        是否支持秒传
        
        Returns:
            bool: 是否支持秒传
        """
        return True
    
    def _path_to_folder_id(self, path: str) -> str:
        """将路径转换为文件夹ID"""
        if path == "/" or path == "":
            return "-11"  # 根目录ID
        
        # 这里简化处理，实际应该根据路径查找对应的文件夹ID
        # 可以通过递归查找或缓存路径映射来实现
        return "-11"
    
    def _convert_to_cloud_file(self, file_data: Dict[str, Any], parent_path: str = "/") -> Optional[CloudFile]:
        """将API返回的文件数据转换为CloudFile对象"""
        try:
            file_id = str(file_data.get('id', ''))
            name = file_data.get('name', '')
            size = int(file_data.get('size', 0))
            is_folder = file_data.get('isFolder', False)
            
            # 构造完整路径
            if parent_path == "/":
                full_path = f"/{name}"
            else:
                full_path = f"{parent_path.rstrip('/')}/{name}"
            
            return CloudFile(
                file_id=file_id,
                name=name,
                size=size,
                file_type=FileType.FOLDER if is_folder else FileType.FILE,
                path=full_path,
                md5=file_data.get('md5', ''),
                create_time=file_data.get('createDate', ''),
                modify_time=file_data.get('lastOpTime', ''),
                parent_id=file_data.get('parentId', '')
            )
            
        except Exception as e:
            print(f"转换文件数据异常: {e}")
            return None